package com.YxyBackMange.Controller.SystemController;

import com.YxyBackMange.Dto.Message;
import com.YxyBackMange.Util.MyUtil;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

@Controller
@RequestMapping("/File")
public class FileController {
    @ResponseBody
    @RequestMapping("/uploadImg")
    public Message uploadFile(HttpSession session, MultipartFile uploadFormFile, HttpServletRequest request) {
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/";
        String strName[] = {".png", ".jpg", ".jpge", ".ico"};
        String filePath = session.getServletContext().getRealPath("/");
        String fileName = "images/";
        String upName = null;
        Message msg = new Message();
        if (!uploadFormFile.isEmpty()) {
            upName = uploadFormFile.getOriginalFilename();
            upName = upName.substring(upName.lastIndexOf('.'));
            boolean flag = false;
            for (String string : strName) {
                if (string.equals(upName)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                fileName += System.currentTimeMillis() + MyUtil.createRandom(6) + upName;
                try {
                    byte[] bytes = uploadFormFile.getBytes();
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath + fileName)));
                    stream.write(bytes);
                    stream.close();
                    msg.setMsg("图片上传成功!");

                    msg.setState(true);
                    msg.setData(basePath + fileName);
                    return msg;
                } catch (Exception e) {
                    e.printStackTrace();
                    msg.setMsg("图片上传失败！");
                }


            }
        }
        msg.setMsg("文件上传失败！");
        return msg;

    }
}
